<?php
namespace Yls\Core;

use Yls;

/**
 * 
 * 身份加密验证类
 * @example
 * $id = 11; //当前ID
 * // 以下假设你拥有一个Cookie类，并且实现了::Set($name)和::Get($name)方法
 * Cookie::Set('id', \Yls\Core\Identify::Set($id)); // 将加密串写入cookie
 * $id = \Yls\Core\Identify::Get(Cookie::Get('id')); // 从cookie中解析出ID 
 * 
 * @author keluo<pycorvn@yeah.net>
 * @since 2015-01-24
 */

class Identity {
    
    /**
     * 加密唯一标识ID
     * @param string 唯一标识$id
     * @return 加密后的字符串
     */
    public static function Set($id) {
        $time = time();
        return self::Encrypt($id.'|'.$time.'|'.md5($id.'|'.$time.'|'.Yls::Instance()->identify));
    }
    
    /**
     * 获取当前已加密过的字符串中隐含的ID
     * @return string 唯一标识ID
     */
    public static function Get($string) {
        $decrypt = self::Decrypt($string);
        $decrypt = explode('|', $decrypt);
        if(!isset($decrypt[2])) return false;
        list($id, $time, $sign) = $decrypt;
        if(0 !== strcasecmp(md5($id.'|'.$time.'|'.Yls::Instance()->identify), $sign)) return fasle;
        
        return $id;
    }
    
    /**
     * 返回以当前用户ID、IP经系统加密函数加密后的字符串
     * @param integer $id 唯一标识ID
     * @return string 加密后的字符串
     */
    private static function Encrypt($text) {
        srand((double)microtime() * 1000000);
        $encrypt_key = md5(rand(0, 32000));
        $ctr = 0;
        $tmp = '';
        for($i = 0; $i < strlen($text); $i++) {
            if($ctr == strlen($encrypt_key)) $ctr = 0;
            $tmp .= substr($encrypt_key, $ctr, 1).(substr($text, $i, 1) ^ substr($encrypt_key, $ctr, 1));
            $ctr++;
        }
        return base64_encode(self::KeyED($tmp));
    }
    
    /**
     * 字符串解密
     * @param string $text 加密字符串
     * @return 解密后的字符串
     */
    private static function Decrypt($text) {
        $text = self::KeyED(base64_decode($text));
        $tmp = '';
        for($i = 0; $i < strlen($text); $i++) {
            $md5 = substr($text, $i, 1);
            $i++;
            $tmp .= (substr($text, $i, 1) ^ $md5);
        }
        return $tmp;
    }
    
    private static function KeyED($text) {
        $encrypt_key = md5(Yls::Instance()->identify);
        $ctr = 0;
        $tmp = '';
        for($i = 0; $i < strlen($text); $i++) {
            if($ctr == strlen($encrypt_key)) $ctr=0;
            $tmp .= substr($text, $i, 1) ^ substr($encrypt_key, $ctr, 1);
            $ctr++;
        }
        return $tmp;
    }
}